<template>
	<div class="article-manager video-icon form-submit" id="shopp-manager">
		<Modal v-model="innerVisible" :title="$t('page.order.detail')" :width="900" @on-ok="handleOk" @on-cancel="handleClose">
			<Form ref="formDynamic" :model="formDynamic" class="attrFrom" @submit.native.prevent :rules="rules">
				<Row :gutter="24">

					<Col span="24" v-if="this.customerId == 0">
					<a @click="addProduct()" size="small"><Button type="primary" icon="ios-add-circle-outline">{{$t('page.customer.select_customer')}}</Button></a>
					</Col>
					<Col span="24">
					    <Col  span="24" class="mb15">
					        <FormItem :label="$t('page.customer.visiting_clients')+'：'" prop="customer_id" class="vertical-layout">
					            <Input
					                    v-model="formDynamic.company"
					                    :placeholder="$t('page.customer.visiting_clients')"
										disabled
					            />
					        </FormItem>
					    </Col>
					</Col>
					<Col span="24">
					    <Col span="24" class="mb15">
					        <FormItem :label="$t('page.customer.visit_time')+'：'" prop="visit_time" class="vertical-layout">
								<!-- <br>
								<div style="margin-top: 5px;"></div> -->
								<DatePicker 
								    type="datetime" 
								    v-model="formDynamic.visit_time" 
								    format="yyyy-MM-dd HH:mm" 
								    :placeholder="$t('page.customer.select_visit_time')" 
								    style="width: 200px"
									disabled
								/>
					        </FormItem>
					    </Col>
					</Col>
					<Col span="24">
					    <Col span="24" class="mb15">
					        <FormItem :label="$t('page.stock.note')+'：'" prop="remarks" class="vertical-layout">
					            <Input
					                    v-model="formDynamic.remarks"
					                    type="textarea"
					                    :autosize="{ minRows: 6, maxRows: 10 }"
					                    :placeholder="$t('page.stock.note')"
										disabled
					            />
					        </FormItem>
					    </Col>
					</Col>
					
					<!-- 修改后的时间线模块 - 输入框在最上面 -->
					<Col span="24">
					    <Col span="24" class="mb15">
					        <FormItem :label="$t('page.customer.communication_records')+'：'" class="vertical-layout">
					            <div class="communication-timeline">
					                <!-- 回复输入框放在最上面 -->
					                <div class="reply-section-top">
					                    <h4 class="reply-title">{{$t('page.customer.send_a_new_message')}}</h4>
					                    <Input
					                            v-model="replyContent"
					                            type="textarea"
					                            :rows="3"
					                            :placeholder="$t('page.customer.communication_records_input')"
					                            style="margin-bottom: 10px;"
					                            @on-input="handleInput"
					                        />
					                        <div style="text-align: right; color: #999; font-size: 12px;">
					                            {{ replyContent.length }}/200
					                        </div>
					                    <div class="reply-actions">
					                        <Button type="primary" @click="sendReply" :loading="replyLoading">
					                            {{ replyLoading ? $t('page.customer.sending') : $t('page.customer.send_a_reply') }}
					                        </Button>
					                        <Button @click="clearReply" style="margin-left: 10px;">{{$t('page.product.clear')}}</Button>
					                    </div>
					                </div>
					                
					                <!-- 时间线展示历史记录 -->
					                <div class="timeline-container">
					                    <h4 class="timeline-title">{{$t('page.customer.historical_communication_records')}}</h4>
					                    <!-- <Timeline>
					                        <TimelineItem v-for="(item, index) in communicationList" :key="index">
					                            <p class="time">{{ item.time }}</p>
					                            <p class="content">{{ item.content }}</p>
					                            <p class="author" v-if="item.author"> - {{ item.author }}</p>
					                        </TimelineItem>
											
					                        <TimelineItem v-if="communicationList.length === 0">
					                            <p class="no-data">暂无沟通记录</p>
					                        </TimelineItem>
					                    </Timeline> -->
										<Timeline v-if="communicationList.length > 0">
										        <TimelineItem
										            v-for="(item, index) in communicationList" 
										            :key="index"
										            :color="getTimelineColor(item.type)"
										            :class="`timeline-type-${item.type}`"
										        >
										            <p class="time">{{ item.time }}</p>
										            <p class="content" :class="`content-type-${item.type}`">{{ item.content }}</p>
										            <p class="author" v-if="item.author"> - {{ item.author }}</p>
										        </TimelineItem>
										        
										        <TimelineItem v-if="communicationList.length === 0">
										            <p class="no-data">{{$t('page.product.no_data')}}</p>
										        </TimelineItem>
										</Timeline>
										<div v-else>{{$t("page.product.no_data")}}</div>
					                </div>
					            </div>
					        </FormItem>
					    </Col>
					</Col>
				</Row>
			</Form>
			<!-- 自定义底部按钮 -->
			<!-- <template #footer>
				<div class="custom-modal-footer">
					<Button type="primary" size="large" @click="submit">
						{{$t('page.product.submit')}}
					</Button>
				</div>
			</template> -->
		</Modal>
	</div>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from "vuex";
	import {
		storeCustomerListApi,
		createStoreCustomreAccessApi,
		storeCustomerAccessDetailApi,
		getQuestionListApi,
		addQuestionApi,
		getUserInfoApi,
	} from "@/api/storeCustomer";
	import {
		createActivityProductApi,
	} from '@/api/capital'
	import {
		productInfoApi,
		activityProductListInfo
	} from "@/api/product";
	export default {
		name: 'customerInfo',
		props: {
			visible: {
				type: Boolean,
				default: false
			},
			activityId: {
				type: Number,
				default: null
			},
			customerId: {
			    type: Number,
			    default: 0
			  }
		},
		data() {
			return {
				loading: false,
				modal: false,
				innerVisible: false,
				productShow: false,
				total: 0,
				ids: 0,
				productSearchsData: {
					store_name: "",
					type: 1,
					activity_id:0,
					page: 1,
					limit: 15,
				},
				userInfo:{
					account:"",
					real_name:"",
				},
				images: [],
				urlList: [],
				others: [],
				productList: [],
				radioProduct: {
					skuList: []
				},
				checkPidList: [],
				formDynamic: {

				},
				// 时间线相关数据
				communicationList: [], // 沟通记录列表
				replyContent: '', // 回复内容
				replyLoading: false, // 回复加载状态
				rules: {
				    customer_id: [
				        { required: true, message: "请选择客户", trigger: "blur" },
				    ],
					visit_time: [
					    { required: true, message: "请选择来访时间", trigger: "blur" },
					],
					remarks: [
					    { required: true, message: "请填写备注", trigger: "blur" },
					],
				},
			};
		},
		watch: {
			visible(val) {
				this.innerVisible = val
				if (val) {
					this.handleClose();
					console.log("打开弹窗, 客户ID:", this.customerId);
					this.replyContent = ""
					if(this.customerId > 0){
						this.getDetail(this.customerId)
						this.loadCommunicationHistory(this.customerId) // 加载沟通记录
						this.getUserInfo()
					}else{
						this.clearData();
					}
				}
			},
			innerVisible(val) {
				this.$emit("update:visible", val)
			},
			// 监听radioProduct变化，确保数据格式正确
			  radioProduct: {
			    handler(newVal) {
			      if (newVal.skuList) {
			        this.$nextTick(() => {
			          this.initActivityStockData();
			        });
			      }
			    },
			    deep: true,
			    immediate: true
			  }
		},
		created() {
		},
		computed: {
			labelWidth() {
				return this.isMobile ? undefined : 120;
			},
			...mapState("admin/layout", ["isMobile", "menuCollapse"]),
			// 计算属性：格式化标签数据
			customerTags() {
				return this.customerData.tags || [];
			},
			labelPosition() {
				return this.isMobile ? "top" : "right";
			},
			goodsColumns(){
				return [{
						title: "ID",
						key: "id",
						width: 80
					},
					{
						title: "客户名称",
						key: "company"
					},
					{
						title: "地址",
						slot: "state",
					
					},
					{
						title: "邮箱",
						key: "email"
					}
				]
			},
			skuColumns(){
				return [{
						title: "SKU ID",
						key: "id",
						width: 80
					},
					{
						title: $t('page.product.specification'),
						key: "suk"
					},
					{
						title: $t('page.product.original_price'),
						key: "price"
					},
					{
						title: $t('page.activity.event_price_title'),
						key: "activity_price",
						slot: "activity_price"
					},
					{
						title: $t('page.stock.warehouse'),
						key: "warehouse",
						slot: "warehouse"
					},
					{
						title: $t('page.stock.stock'),
						key: "stock",
						slot: "stock"
					},
					{
						title: $t('page.activity.event_stock_title'),
						key: "activity_stock",
						slot: "activity_stock"
					}
				]
			}
		},
		methods: {
			// 根据类型获取时间线颜色
			    getTimelineColor(type) {
			        const colorMap = {
			            1: 'green',    // 成功/积极
			            2: 'orange',   // 警告/注意  
			            3: 'red',      // 错误/问题
			            4: 'blue',     // 信息/普通
			            5: 'gray'      // 中性/其他
			        };
			        return colorMap[type] || 'blue';
			    },
			    
			    // 根据类型获取显示文本
			    getTypeText(type) {
			        const typeMap = {
			            1: '积极',
			            2: '注意',
			            3: '问题',
			            4: '信息',
			            5: '其他'
			        };
			        return typeMap[type] || '';
			    },
			handleInput(value) {
			            // 如果超过200字符，自动截断
			            if (value.length > 200) {
			                this.replyContent = value.slice(0, 200);
			            }
			        },
			getDetail(id) {
				storeCustomerAccessDetailApi(id)
					.then((res) => {
						this.formDynamic = res.data.info;
					})
					.catch((res) => {
						this.$Message.error(res.msg);
					});
			},
			
			// 加载沟通记录
			loadCommunicationHistory(customerId) {
				// 模拟API调用，实际项目中替换为真实API
				getQuestionListApi(customerId)
					.then((res) => {
						this.communicationList = res.data.info;
					})
					.catch((res) => {
						this.$Message.error(res.msg);
					});
				// setTimeout(() => {
				// 	this.communicationList = [
				// 		{
				// 			time: '2024-01-16 16:45',
				// 			content: '包装设计稿已发送给客户确认',
				// 			author: '设计部 - 王五'
				// 		},
				// 		{
				// 			time: '2024-01-16 09:15',
				// 			content: '客户确认订单，需要定制包装',
				// 			author: '销售经理 - 张三'
				// 		},
				// 		{
				// 			time: '2024-01-15 14:20',
				// 			content: '已发送产品报价单和样品信息',
				// 			author: '客服 - 李四'
				// 		},
				// 		{
				// 			time: '2024-01-15 10:30',
				// 			content: '客户咨询产品价格和交货期',
				// 			author: '销售经理 - 张三'
				// 		}
				// 	];
				// }, 500);
			},
			getUserInfo() {
				getUserInfoApi()
					.then((res) => {
						this.userInfo = res.data.info;
					})
					.catch((res) => {
						this.$Message.error(res.msg);
					});
			},
			// 发送回复
			sendReply() {
				if (!this.replyContent.trim()) {
					this.$Message.error('请输入回复内容');
					return;
				}
				
				this.replyLoading = true;
				let data = {
				  message: this.replyContent
				}
				addQuestionApi(data, this.customerId)
					.then((res) => {
						// 添加新的回复到时间线顶部
						const now = new Date();
						const timeString = `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}-${now.getDate().toString().padStart(2, '0')} ${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;
						
						this.communicationList.unshift({
							time: timeString,
							content: this.replyContent,
							author: this.userInfo.account,
							type:2,
						});
						
						this.replyContent = '';
						this.replyLoading = false;
						this.$Message.success('回复发送成功');
					})
					.catch((res) => {
						this.$Message.error(res.msg);
					});
				
				// 模拟API调用发送回复
				// setTimeout(() => {
				// 	// 添加新的回复到时间线顶部
				// 	const now = new Date();
				// 	const timeString = `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}-${now.getDate().toString().padStart(2, '0')} ${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;
					
				// 	this.communicationList.unshift({
				// 		time: timeString,
				// 		content: this.replyContent,
				// 		author: '当前用户'
				// 	});
					
				// 	this.replyContent = '';
				// 	this.replyLoading = false;
				// 	this.$Message.success('回复发送成功');
				// }, 1000);
			},
			
			// 清空回复
			clearReply() {
				this.replyContent = '';
			},
			
			clearData(){
				this.formDynamic = {}
				this.communicationList = []
				this.replyContent = ''
			},

			//分页
			pageChange(page) {
				this.productSearchsData.page = page;
				this.getProductList();
			},
			handleOk() {
				this.$emit('update:modalVisible', false);
				// 处理确认逻辑
			},
			handleClose(){
				this.radioProduct = {}
			},
			closeModal() {
				this.innerVisible = false
			}
		}
	};
</script>

<style scoped>
	/* 全局样式 */
	.customer-info-modal {
		padding: 24px;
	}

	/* 统计卡片样式 */
	.stats-cards {
		display: grid;
		grid-template-columns: repeat(4, 1fr);
		gap: 16px;
		margin-bottom: 24px;
	}

	.stat-card {
		background: #ffffff;
		border-radius: 8px;
		padding: 16px;
		box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
		transition: all 0.3s ease;
		border: 1px solid #ebedf0;
	}

	.stat-card:hover {
		box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
		transform: translateY(-2px);
	}

	.card-value {
		font-size: 16px;
		font-weight: 600;
		color: #1d2129;
		margin-bottom: 4px;
	}

	.card-label {
		font-size: 14px;
		color: #86909c;
	}

	/* 主要内容区域 */
	.main-content {
		display: flex;
		gap: 24px;
	}

	/* 订单历史区域 */
	.order-history {
		flex: 2;
	}

	.section-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 16px;
	}

	.section-title {
		font-size: 18px;
		font-weight: 500;
		color: #1d2129;
	}

	.order-card {
		background: #ffffff;
		border-radius: 8px;
		padding: 16px;
		margin-bottom: 16px;
		box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
		border: 1px solid #ebedf0;
		transition: all 0.3s ease;
	}

	.order-card:hover {
		box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
	}

	.order-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 12px;
	}

	.order-meta {
		display: flex;
		align-items: center;
		gap: 8px;
	}

	.order-number {
		font-size: 16px;
		font-weight: 500;
		color: #1d2129;
	}

	.order-date {
		font-size: 14px;
		color: #86909c;
	}

	.order-status {
		padding: 4px 8px;
		border-radius: 4px;
		font-size: 14px;
		font-weight: 500;
	}

	.status-pending {
		background: #fff7e6;
		color: #fa8c16;
	}

	.order-customer {
		font-size: 14px;
		color: #4e5969;
		margin-bottom: 12px;
	}

	.order-items {
		margin-bottom: 12px;
	}

	.order-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 8px 0;
		border-bottom: 1px solid #f2f3f5;
	}

	.order-item:last-child {
		border-bottom: none;
	}

	.product-info {
		display: flex;
		align-items: center;
		gap: 8px;
	}

	.product-quantity {
		color: #86909c;
	}

	.product-name {
		color: #1d2129;
	}

	.product-price {
		font-weight: 500;
		color: #1d2129;
	}

	.order-total {
		display: flex;
		justify-content: flex-end;
		align-items: center;
		gap: 8px;
		font-size: 16px;
		font-weight: 500;
		color: #1d2129;
	}

	/* 客户信息区域 */
	.customer-profile {
		flex: 1;
		display: flex;
		flex-direction: column;
		gap: 16px;
	}

	.profile-card {
		background: #ffffff;
		border-radius: 8px;
		box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
		border: 1px solid #ebedf0;
		transition: all 0.3s ease;
	}

	.profile-card:hover {
		box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
	}

	.card-header {
		padding: 16px;
		border-bottom: 1px solid #f2f3f5;
	}

	.card-title {
		font-size: 16px;
		font-weight: 500;
		color: #1d2129;
	}

	.card-body {
		padding: 16px;
	}

	.info-row {
		display: flex;
		align-items: center;
		margin-bottom: 8px;
	}

	.info-label {
		width: 140px;
		color: #86909c;
	}

	.info-value {
		color: #1d2129;
	}

	.company-name {
		font-size: 16px;
		font-weight: 500;
		color: #1d2129;
		margin-bottom: 8px;
	}

	.credit-value {
		font-size: 16px;
		color: #1d2129;
	}

	.tag-list {
		display: flex;
		flex-wrap: wrap;
		gap: 8px;
	}

	.ivu-btn-ghost {
		color: #fff;
		background: #161515 !important;
	}

	.tag {
		padding: 4px 8px;
		background: #f2f3f5;
		border-radius: 4px;
		font-size: 14px;
		color: #4e5969;
	}

	.view-all-link {
		float: right;
		color: #4c4e51;
		/* 正常状态颜色 */
		cursor: pointer;
		/* 鼠标变成手型 */
		transition: color 0.2s;
		/* 添加颜色过渡效果 */
	}

	.view-all-link:hover {
		color: #000000;
		/* 悬停状态颜色 */
		text-decoration: underline;
		/* 可选：添加下划线增强交互感 */
	}
	/* 灰色不可选行样式 */
	.row-disabled {
	  background-color: #f5f5f5 !important;
	  color: #999 !important;
	  cursor: not-allowed;
	}
	
	/* 时间线样式 */
	.communication-timeline {
		border: 1px solid #e8eaec;
		border-radius: 4px;
		padding: 16px;
		background: #fafafa;
	}
	
	/* 顶部回复区域 */
	.reply-section-top {
		background: #ffffff;
		border: 1px solid #e8eaec;
		border-radius: 4px;
		padding: 16px;
		margin-bottom: 20px;
	}
	
	.reply-title {
		font-size: 16px;
		font-weight: 600;
		color: #17233d;
		margin-bottom: 12px;
	}
	
	.reply-actions {
		display: flex;
		justify-content: flex-start;
		align-items: center;
	}
	
	/* 时间线容器 */
	.timeline-container {
		background: #ffffff;
		border: 1px solid #e8eaec;
		border-radius: 4px;
		padding: 16px;
		max-height: 300px;
		overflow-y: auto;
	}
	
	.timeline-title {
		font-size: 16px;
		font-weight: 600;
		color: #17233d;
		margin-bottom: 16px;
		padding-bottom: 8px;
		border-bottom: 1px solid #f0f0f0;
	}
	
	.time{
		font-size: 14px;
		font-weight: bold;
		margin-bottom: 5px;
		color: #2d8cf0;
	}
	
	.content{
		padding-left: 5px;
		font-size: 14px;
		color: #515a6e;
		margin-bottom: 3px;
		line-height: 1.5;
	}
	
	.author {
		padding-left: 5px;
		font-size: 12px;
		color: #808695;
		font-style: italic;
	}
	
	.no-data {
		text-align: center;
		color: #c5c8ce;
		font-style: italic;
		padding: 20px 0;
	}
	.timeline-container {
	    position: relative;
	}
	
	/* 不同类型的时间线节点颜色 */
	.timeline-type-1 .ivu-timeline-item-head {
	    background-color: #19be6b; /* 成功/积极 - 绿色 */
	    border-color: #19be6b;
	}
	
	.timeline-type-2 .ivu-timeline-item-head {
	    background-color: #ff9900; /* 警告/注意 - 橙色 */
	    border-color: #ff9900;
	}
	
	.timeline-type-3 .ivu-timeline-item-head {
	    background-color: #ed4014; /* 错误/问题 - 红色 */
	    border-color: #ed4014;
	}
	
	.timeline-type-4 .ivu-timeline-item-head {
	    background-color: #2d8cf0; /* 信息/普通 - 蓝色 */
	    border-color: #2d8cf0;
	}
	
	.timeline-type-5 .ivu-timeline-item-head {
	    background-color: #80848f; /* 中性/其他 - 灰色 */
	    border-color: #80848f;
	}
	
	/* 内容样式 */
	.time {
	    font-size: 12px;
	    color: #999;
	    margin-bottom: 4px;
	}
	
	.content {
	    font-size: 14px;
	    line-height: 1.5;
	    margin-bottom: 4px;
	}
	
	/* 不同类型的内容样式 */
	.content-type-1 {
	    color: #19be6b;
	    font-weight: 500;
	}
	
	.content-type-2 {
	    color: #ff9900;
	    font-weight: 500;
	}
	
	.content-type-3 {
	    color: #ed4014;
	    font-weight: 500;
	}
	
	.content-type-4 {
	    color: #2d8cf0;
	    font-weight: 500;
	}
	
	.content-type-5 {
	    color: #515a6e;
	}
	
	.author {
	    font-size: 12px;
	    color: #c5c8ce;
	    font-style: italic;
	}
	
	/* 类型标签 */
	.type-tag {
	    position: absolute;
	    top: 0;
	    right: 0;
	    padding: 2px 6px;
	    font-size: 12px;
	    border-radius: 3px;
	    background: #f8f8f9;
	    color: #515a6e;
	    border: 1px solid #e8eaec;
	}
	
	/* 无数据样式 */
	.no-data {
	    text-align: center;
	    color: #c5c8ce;
	    font-size: 14px;
	    padding: 20px 0;
	}
</style>